package com.liao.domain.strategy.service.rule.chain.factory;

import com.liao.domain.strategy.model.entity.StrategyEntity;
import com.liao.domain.strategy.repository.IStrategyRepository;
import com.liao.domain.strategy.service.rule.chain.ILogicChain;
import lombok.*;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author long
 * @Description 工厂
 * @Date 2024-08-26 12:41
 */
@Service
public class DefaultChainFactory {
    private final Map<String, ILogicChain> logicChainGroup;
    protected final IStrategyRepository repository;

    public DefaultChainFactory(Map<String, ILogicChain> logicChainGroup, IStrategyRepository repository) {
        this.logicChainGroup = logicChainGroup;
        this.repository = repository;
    }

    public ILogicChain openLogicChain(Long strategyId) {
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategyEntity.ruleModels();
        //如果未配置策略规则，则只装填一个默认责任链
        if (ruleModels == null || ruleModels.length == 0) {
            return logicChainGroup.get("default");
        }

        // 按照配置顺序装填用户配置的责任链；rule_blacklist、rule_weight
        ILogicChain iLogicChain = logicChainGroup.get(ruleModels[0]);
        ILogicChain current = iLogicChain;
        for (int i = 1; i < ruleModels.length; i++) {
            ILogicChain nextChain = logicChainGroup.get(ruleModels[i]);
            current = current.appendNext(nextChain);
        }
        current.appendNext(logicChainGroup.get("default"));

        return iLogicChain;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /**
         * 抽奖奖品ID - 内部流转使用
         */
        private Long awardId;
        /**
         *
         */
        private String logicModel;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WHITELIST("rule_whitelist", "白名单规则"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }
}
